package com.qyhl.webtv.module_live.teletext.program;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NotchSizeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.ProgramDetailBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

import static com.shuyu.gsyvideoplayer.video.base.GSYVideoView.CURRENT_STATE_PLAYING;


/**
 * Created by qyhl on 2018/1/4.
 *
 * @author qyhl
 *         电视直播
 */

@Route(path = ARouterPathConstant.LIVE_VIDEO)
public class LiveVideoActivity extends BaseActivity implements LiveNormalContract.LiveNormalView {
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.mtitle)
    TextView title;
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.scan_num)
    TextView scanNum;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.menu_list)
    ListView menuListView;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.menu_layout)
    LinearLayout menuLayout;
    @BindView(R2.id.content_mask)
    LoadingLayout contentMask;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private LiveNormalPresenter mPresenter;
    @Autowired(name = "id")
    String programId;

    private ProgramDetailBean mBean;


    private List<ProgramDetailBean.ProgramNoticeList> mDataList;

    private List<ProgramDetailBean.ProgramNoticeList.Program> mMenuList;


    private CommonAdapter commonAdapter;

    private com.zhy.adapter.recyclerview.CommonAdapter mAdapter;

    private LoadingDialog.Builder builder;

    private GSYVideoOptionBuilder gsyVideoOption;

    private EmptyWrapper emptyWrapper;

    private Timer timer;

    private TimerTask timerTask;

    private Calendar mCalendar;

    private int curDay;//当前日期

    private int mWeekNum;

    private int mMenuNum;
    /**
     * 是否为刘海屏
     */
    private boolean isNotch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isNotch = NotchSizeUtil.hasNotchInScene(this);
        if(!isNotch){
            if (Build.VERSION.SDK_INT > 19) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.live_activity_live_video;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new LiveNormalPresenter(this);
        initView();
        setListenter();
        mPresenter.getDetail(programId);
        mPresenter.click(programId);
    }




    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        contentMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();
        mMenuList = new ArrayList<>();

        builder = new LoadingDialog.Builder(LiveVideoActivity.this);
        builder.setTitle("切换中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        menuListView.setAdapter(commonAdapter = new CommonAdapter<ProgramDetailBean.ProgramNoticeList>(this, R.layout.live_item_program_menulist, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ProgramDetailBean.ProgramNoticeList o, int position) {
                TextView week = holder.getView(R.id.week);
                TextView date = holder.getView(R.id.date);

                if (o.isSelected()) {
                    week.setTextColor(getResources().getColor(R.color.global_base));
                    date.setTextColor(getResources().getColor(R.color.global_base));
                } else {
                    week.setTextColor(getResources().getColor(R.color.global_black_lv1));
                    date.setTextColor(getResources().getColor(R.color.global_gray_lv2));
                }

                if (o.getIsLive() == 1) {
                    week.setText("今天");
                    date.setText(o.getsDate());
                } else {
                    week.setText(o.getsWeek());
                    date.setText(o.getsDate());
                }
            }
        });

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        mAdapter = new com.zhy.adapter.recyclerview.CommonAdapter<ProgramDetailBean.ProgramNoticeList.Program>(this, R.layout.live_item_live_menu, mMenuList) {

            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder viewHolder, ProgramDetailBean.ProgramNoticeList.Program item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                ImageView status = viewHolder.getView(R.id.status);
                ImageView status_dot = viewHolder.getView(R.id.status_dot);
                TextView time = viewHolder.getView(R.id.time);
                //选中状态
                if (item.isSelected()) {
                    status.setVisibility(View.VISIBLE);
                    title.setTextColor(getResources().getColor(R.color.global_base));

                    status_dot.setImageResource(R.drawable.status_dot_playing);

                    Glide.with(LiveVideoActivity.this)
                            .load(R.drawable.status_playing)
                            .into(status);

                    time.setTextColor(getResources().getColor(R.color.global_base));
                } else {
                    if (item.getStatus() == 1) {
                        status.setVisibility(View.VISIBLE);
                        title.setTextColor(getResources().getColor(R.color.global_black_lv1));

                        status_dot.setImageResource(R.drawable.status_dot_review);

                        Glide.with(LiveVideoActivity.this)
                                .load(R.drawable.status_review)
                                .into(status);

                        time.setTextColor(getResources().getColor(R.color.gray_status_menu));
                    } else if (item.getStatus() == 0) {
                        status.setVisibility(View.VISIBLE);
                        title.setTextColor(getResources().getColor(R.color.global_black_lv1));

                        status_dot.setImageResource(R.drawable.status_dot_review);

                        Glide.with(LiveVideoActivity.this)
                                .load(R.drawable.status_live)
                                .into(status);

                        time.setTextColor(getResources().getColor(R.color.gray_status_menu));
                    } else {
                        title.setTextColor(getResources().getColor(R.color.gray_status_menu));

                        status_dot.setImageResource(R.drawable.status_dot_foreshow);

                        status.setVisibility(View.GONE);

                        time.setTextColor(getResources().getColor(R.color.gray_status_menu));
                    }
                }

                time.setText(item.getsTime());

                title.setText(item.getName());
            }
        };

        emptyWrapper = new EmptyWrapper(mAdapter);
        emptyWrapper.setEmptyView(R.layout.live_layout_list_emptyview);
        recyclerView.setAdapter(emptyWrapper);

    }

    @Override
    protected void setListener() {
        setListenter();
    }
    /**
     * 设置监听
     */
    protected void setListenter() {
        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(programId);
        });

        //分享
        shareBtn.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(LiveVideoActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                if (mBean != null) {
                    MShareBoard shareBoard = new MShareBoard(LiveVideoActivity.this,programId,mBean.getProgram().getName(),mBean.getProgram().getCoverImg(),mBean.getProgram().getDetail(), CommonUtils.getInstance().getBannerId(),14);
                    shareBoard.showPopupWindow();
                } else {
                    Toasty.normal(LiveVideoActivity.this, "请等待信息加载...", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(LiveVideoActivity.this);
            }
        }));

        //节目单点击
        menuListView.setOnItemClickListener((parent, view, position, id) -> {
            mWeekNum = position;
            for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                if (i == mWeekNum) {
                    mBean.getProgramDay().get(i).setSelected(true);
                } else {
                    mBean.getProgramDay().get(i).setSelected(false);
                }
            }
            mDataList.clear();
            mDataList.addAll(mBean.getProgramDay());
            commonAdapter.notifyDataSetChanged();

            mMenuList.clear();
            mMenuList.addAll(mDataList.get(mWeekNum).getProgram());
            emptyWrapper.notifyDataSetChanged();
        });

        //节目单内容点击
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (mMenuList.get(position).getStatus() == 2) {
                    Toasty.normal(LiveVideoActivity.this, "尚未开始，敬请期待...").show();
                } else {
                    mMenuNum = position;
                    for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                        for (int j = 0; j < mBean.getProgramDay().get(i).getProgram().size(); j++) {
                            if (i == mWeekNum && j == mMenuNum) {
                                mBean.getProgramDay().get(i).getProgram().get(j).setSelected(true);
                                if (mBean.getProgramDay().get(i).getProgram().get(j).getStatus() == 0) {
                                    videoPlayer.setMode(QYVideoPlayer.PlayMode.LIVE);
                                    videoPlayer.release();
                                    videoPlayer.setUp(mBean.getProgram().getHlsUrl(), true, " ");
                                    videoPlayer.getStartButton().performClick();
                                } else {
                                    builder.show();
                                    videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
                                    mPresenter.getPlayPath(mBean.getProgram().getStreamAddressName(), mBean.getProgramDay().get(i).getProgram().get(j).getStartTime(), mBean.getProgramDay().get(i).getProgram().get(j).getEndTime());
                                }
                            } else {
                                mBean.getProgramDay().get(i).getProgram().get(j).setSelected(false);
                            }
                        }
                    }
                    mMenuList.clear();
                    mMenuList.addAll(mBean.getProgramDay().get(mWeekNum).getProgram());

                    mAdapter.notifyDataSetChanged();
                    emptyWrapper.notifyDataSetChanged();

                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        videoPlayer.getBackButton().setOnClickListener(v -> {
            if (GSYVideoManager.backFromWindowFull(LiveVideoActivity.this)) {

            } else {
                finish();
            }
        });

        builder.getmDialog().setOnDismissListener(dialog -> {

        });


    }

    @Override
    public void setDetail(ProgramDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        mBean = bean;

        mCalendar = Calendar.getInstance();
        curDay = mCalendar.get(Calendar.DAY_OF_MONTH);
        //标题
        title.setText(mBean.getProgram().getName());

        //浏览数
        scanNum.setText(StringUtils.transformNum(mBean.getProgram().getHits() + ""));

        ImageView imageView = new ImageView(this);
        Glide.with(this)
                .load(mBean.getProgram().getCoverImg())
                .apply(new RequestOptions().centerCrop().error(R.drawable.icon_live_no_img).placeholder(R.drawable.icon_live_no_img))
                .into(imageView);
        //设置封面图
        videoPlayer.setThumbImageView(imageView);

        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.setMode(QYVideoPlayer.PlayMode.LIVE);
        videoPlayer.setUp(mBean.getProgram().getHlsUrl() == null ? "" : mBean.getProgram().getHlsUrl(), true, "");

        videoPlayer.getFullscreenButton().setOnClickListener(v -> {
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            videoPlayer.startWindowFullscreen(LiveVideoActivity.this, true, true);
        });

        videoPlayer.setStateListener(new QYVideoPlayer.StateListener() {
            @Override
            public void state(boolean isShow) {
                if (isShow) {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                } else {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void closeRadio() {

            }
        });

        videoPlayer.getBackButton().setOnClickListener(v -> finish());

        videoPlayer.getStartButton().performClick();//自动播放


        //是否有节目单
        if (mBean.getProgram().getIsNotice() == 0) {
            summary.setVisibility(View.VISIBLE);
            menuLayout.setVisibility(View.GONE);
            //是否有简介
            if (StringUtils.isEmpty(mBean.getProgram().getDetail())) {
                contentMask.setStatus(LoadingLayout.Empty);
                contentMask.setEmptyText("小编正在准备内容");
            } else {
                contentMask.setStatus(LoadingLayout.Success);
                summary.setText(mBean.getProgram().getDetail());
            }
        } else {
            summary.setVisibility(View.GONE);
            menuLayout.setVisibility(View.VISIBLE);

            if (mBean.getProgramDay() != null && mBean.getProgramDay().size() > 0) {
                contentMask.setStatus(LoadingLayout.Success);

                mDataList.clear();
                //初始化选中节目单
                for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                    if (mBean.getProgramDay().get(i).getIsLive() == 1) {
                        mWeekNum = i;
                        mBean.getProgramDay().get(i).setSelected(true);
                    } else {
                        mBean.getProgramDay().get(i).setSelected(false);
                    }
                }

                for (int i = 0; i < mBean.getProgramDay().get(mWeekNum).getProgram().size(); i++) {
                    if (mBean.getProgramDay().get(mWeekNum).getProgram().get(i).getStatus() == 0) {
                        mMenuNum = i;
                        mBean.getProgramDay().get(mWeekNum).getProgram().get(i).setSelected(true);
                    } else {
                        mBean.getProgramDay().get(mWeekNum).getProgram().get(i).setSelected(false);
                    }
                }

                mDataList.clear();
                mDataList.addAll(mBean.getProgramDay());

                mMenuList.clear();
                mMenuList.addAll(mBean.getProgramDay().get(mWeekNum).getProgram());

                mAdapter.notifyDataSetChanged();
                commonAdapter.notifyDataSetChanged();
                emptyWrapper.notifyDataSetChanged();

            } else {
                contentMask.setStatus(LoadingLayout.Empty);
                contentMask.setEmptyText("小编正在准备内容");
            }
        }

        //存在节目单时，定时刷新正在播放的节目单
        if (mBean.getProgram().getIsNotice() != 0) {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    long time = System.currentTimeMillis();//当前时间
                    int weekPostion = 0;//当前正在直播的日期
                    int menuPostion = 0;//当前正在直播的节目序号
                    for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                        if (mBean.getProgramDay().get(i).getIsLive() == 1) {
                            weekPostion = i;
                        }
                    }
                    for (int i = 0; i < mBean.getProgramDay().get(weekPostion).getProgram().size(); i++) {
                        if (mBean.getProgramDay().get(weekPostion).getProgram().get(i).getStatus() == 0) {
                            menuPostion = i;
                        }
                    }
                    //判断当前播放的是否是今日最后一条
                    if (menuPostion == (mBean.getProgramDay().get(weekPostion).getProgram().size() - 1)) {
                        //判断是否过了一天
                        if (curDay < mCalendar.get(Calendar.DAY_OF_MONTH)) {
                            //判断当前是否在直播最后一条或者没有在播放
                            if ((mWeekNum == weekPostion && menuPostion == mMenuNum) || videoPlayer.getCurrentState() != CURRENT_STATE_PLAYING) {
                                timer.cancel();
                                videoPlayer.release();
                                mPresenter.getDetail(programId);
                            }
                        }
                    } else {
                        //下一个节目开始时间
                        try {
                            String startTime = mBean.getProgramDay().get(weekPostion).getProgram().get(menuPostion + 1).getStartTime();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            long tTime = simpleDateFormat.parse(startTime).getTime();
                            //判断下一个节目是否已经开始
                            if (time >= tTime) {
                                for (int i = 0; i < mBean.getProgramDay().get(weekPostion).getProgram().size(); i++) {
                                    if (i == (menuPostion + 1)) {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(0);
                                    } else if (i < (menuPostion + 1)) {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(1);
                                    } else {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(2);
                                    }
                                }
                                mHandler.sendEmptyMessage(0);
                                if ((mWeekNum == weekPostion && menuPostion == mMenuNum)) {
                                    mHandler.sendEmptyMessage(1);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            timer.schedule(timerTask, 0, 10000);
        }


        menuListView.setSelection(mWeekNum);
    }

    @Override
    public void setNetError(String msg) {
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setNoNetworkText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setEmpty(String msg) {
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void getPathError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg).show();
        videoPlayer.release();
        videoPlayer.setUp("", true, " ");
        videoPlayer.getStartButton().performClick();
    }

    @Override
    public void getPathSuccess(String url) {
        builder.dismiss();
        videoPlayer.release();
        videoPlayer.setUp(url, true, " ");
        videoPlayer.getStartButton().performClick();
    }

    @Override
    public void cancel() {
        builder.dismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (QYVideoPlayer.getPlayMode() == QYVideoPlayer.PlayMode.LIVE) {
            if (videoPlayer.isIfCurrentIsFullscreen()) {
                videoPlayer.getStartButton().performClick();
            } else {
                videoPlayer.startPlayLogic();
            }
        } else {
            videoPlayer.onVideoResume();
        }
        //umeng
        MobclickAgent.onPageStart("电视直播");
        MobclickAgent.onResume(this);

    }


    @Override
    protected void onPause() {
        videoPlayer.onVideoPause();
        //umeng
        MobclickAgent.onPageEnd("电视直播");
        MobclickAgent.onPause(this);
        super.onPause();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.release();
    }



    private static class MyHandler extends Handler {
        private final WeakReference<LiveVideoActivity> mActivity;

        public MyHandler(LiveVideoActivity activity) {
            mActivity = new WeakReference<LiveVideoActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            LiveVideoActivity liveVideoActivity =   mActivity.get();
            switch (msg.what) {
                case 0:
                    liveVideoActivity.mDataList.clear();
                    liveVideoActivity.mDataList.addAll(liveVideoActivity.mBean.getProgramDay());
                    liveVideoActivity.commonAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    for (int i = 0; i < liveVideoActivity.mBean.getProgramDay().get(liveVideoActivity.mWeekNum).getProgram().size(); i++) {
                        if (i == (liveVideoActivity.mMenuNum + 1)) {
                            liveVideoActivity.mBean.getProgramDay().get(liveVideoActivity.mWeekNum).getProgram().get(i).setSelected(true);
                        } else {
                            liveVideoActivity.mBean.getProgramDay().get(liveVideoActivity.mWeekNum).getProgram().get(i).setSelected(false);
                        }
                    }
                    liveVideoActivity.mMenuList.clear();
                    liveVideoActivity.mMenuList.addAll(liveVideoActivity.mBean.getProgramDay().get(liveVideoActivity.mWeekNum).getProgram());
                    liveVideoActivity.mAdapter.notifyDataSetChanged();
                    liveVideoActivity.emptyWrapper.notifyDataSetChanged();
                    liveVideoActivity.mMenuNum += 1;
                    break;
                default:
                    break;
            }
        }
    }

    Handler mHandler = new MyHandler(this);



}
